package com.gg.registration.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gg.common.helper.JWTHelper;
import com.gg.common.result.ResultCodeEnum;
import com.gg.common.utils.RegistrationException;
import com.gg.registration.model.user.UserInfo;
import com.gg.registration.user.service.UserInfoService;
import com.gg.registration.user.service.WeChatApiService;
import com.gg.registration.user.utils.HttpClientUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：  chenjunjia
 * Date：    2022/4/20 21:55
 * WeChat：  China_JoJo_
 */
@Service
public class WeChatApiServiceImpl implements WeChatApiService {

    @Resource
    UserInfoService userInfoService;

    private String appId="wxb47";

    private String appSecret="a72";

    /**
     * 回调返回用户数据
     * @param code 用户扫描微信二维码后，微信端找到此接口，回调此接口，传入的code参数
     * @param state 用户扫描微信二维码后，微信端找到此接口，回调此接口，传入的state参数
     * @return 跳转到前端页面
     */
    @Override
    public Map<String, String> callback(String code, String state) {
        //1、获取临时票据
        System.out.println(code);
        //2、拿着code和微信id和秘钥，请求微信固定地址，得到两个值
        //使用code和appid，以及appsecret 换来 accesstoken
        //%s 占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(
                baseAccessTokenUrl.toString(),
                appId,
                appSecret,
                code);
        //使用httpclient请求这个地址
        String accessTokenInfo = "";
        try {
            //发起请求
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(accessTokenInfo);
        //从字符串获取两个值：openid和access_token
        JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //TODO 判断数据库是否存在微信扫描人的信息，根据openid判断，如果不存在，才添加进去
        UserInfo userInfo = userInfoService.queryUserInfoByOpenid(openid);
        if (null == userInfo) {
            //此用户不存在
            //3、拿着openid和access_token请求微信地址，得到扫描人信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo = null;
            try {
                //发起请求
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(resultUserInfo);
            } catch (Exception e) {
                throw new RegistrationException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }
            //获取用户信息
            JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
            String nickname = resultUserInfoJson.getString("nickname");
            String headimgurl = resultUserInfoJson.getString("headimgurl");

            //封装用户信息,添加到数据库
            userInfo = new UserInfo();
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfo.setOpenid(openid);
            boolean save = userInfoService.save(userInfo);
        }
        //返回name和token字符串
        Map<String,String> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        //使用jwt生成token字符串
        String token = JWTHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        map.put("name", name);

        //判断userInfo是否有手机号，如果手机号为空，返回openid
        //如果手机号不为空，返回openid值是空字符串
        //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
        if (StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", userInfo.getOpenid());//将openid添加进去，返回前端
        }else {
            map.put("openid","");
        }
        return null;
    }
}
